/*
 * Powered By dico
 * Since 2017 - 2018
 */
package com.seeyoui.kensite.bussiness.orderlang.productCategory.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONPath;
import com.google.gson.Gson;
import com.seeyoui.kensite.bussiness.orderlang.productCategory.domain.ProductCategory;
import com.seeyoui.kensite.bussiness.orderlang.productCategory.service.ProductCategoryService;
import com.seeyoui.kensite.common.base.controller.BaseController;
import com.seeyoui.kensite.common.base.domain.EasyUIDataGrid;
import com.seeyoui.kensite.common.base.domain.Page;
import com.seeyoui.kensite.common.constants.StringConstant;
import com.seeyoui.kensite.common.util.DateUtils;
import com.seeyoui.kensite.common.util.RequestResponseUtil;
import com.seeyoui.kensite.common.util.Result;
import com.seeyoui.kensite.common.util.StringUtils;
import com.seeyoui.kensite.common.util.excel.ExportExcel;

/**
 * ProductCategory
 * 
 * @author dico
 * @version 2.0
 * @since 1.0
 * @date 2018-02-07
 */

@Controller
@RequestMapping(value = "productCategory")
public class ProductCategoryController extends BaseController {

    @Autowired
    private ProductCategoryService productCategoryService;

    /**
     * 展示列表页面
     * 
     * @param modelMap
     * @param module
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("productCategory:productCategory:view")
    @RequestMapping(value = "/{page}")
    public ModelAndView view(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            @PathVariable String page) throws Exception {
        return new ModelAndView("bussiness/orderlang/productCategory/" + page, modelMap);
    }

    /**
     * 根据ID查询单条数据
     * 
     * @param modelMap
     * @param module
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("productCategory:productCategory:select")
    @RequestMapping(value = "/data/{id}")
    @ResponseBody
    public Object data(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, @PathVariable String id)
            throws Exception {
        ProductCategory productCategory = productCategoryService.findOne(id);
        return productCategory;
    }

    /**
     * 根据ID查询单条数据并返回相应表单
     * 
     * @param modelMap
     * @param module
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("productCategory:productCategory:view")
    @RequestMapping(value = "/form/{page}/{id}")
    public ModelAndView form(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            @PathVariable String page, @PathVariable String id) throws Exception {
        ProductCategory productCategory = productCategoryService.findOne(id);
        modelMap.put("productCategory", productCategory);
        return new ModelAndView("bussiness/orderlang/productCategory/" + page, modelMap);
    }

    /**
     * 获取列表展示数据
     * 
     * @param modelMap
     * @param productCategory
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("productCategory:productCategory:select")
    @RequestMapping(value = "/list/data", method = RequestMethod.POST)
    @ResponseBody
    public Object listData(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            ProductCategory productCategory) throws Exception {
        productCategory.setDelFlag("0");
        List<ProductCategory> productCategoryList = productCategoryService.findList(productCategory);
        int total = productCategoryService.findTotal(productCategory);
        EasyUIDataGrid eudg = new EasyUIDataGrid();
        eudg.setTotal(String.valueOf(total));
        eudg.setRows(productCategoryList);
        return eudg;
    }

    /**
     * 获取列表展示数据带分页器用于jsp自己做分页
     * 
     * @param modelMap
     * @param productCategory
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("productCategory:productCategory:view")
    @RequestMapping(value = "/list/page", method = RequestMethod.POST)
    @ResponseBody
    public Object listPage(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            ProductCategory productCategory) throws Exception {
        productCategory.setDelFlag("0");
        List<ProductCategory> productCategoryList = productCategoryService.findList(productCategory);
        int total = productCategoryService.findTotal(productCategory);
        Page<ProductCategory> page = new Page<ProductCategory>(productCategory.getPage(), productCategory.getRows(), total);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("rows", productCategoryList);
        dataMap.put("page", page);
        return dataMap;
    }

    /**
     * 获取所有数据
     * 
     * @param modelMap
     * @param productCategory
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("productCategory:productCategory:select")
    @RequestMapping(value = "/list/all", method = RequestMethod.POST)
    @ResponseBody
    public Object listAll(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            ProductCategory productCategory) throws Exception {
        productCategory.setDelFlag("0");
        List<ProductCategory> productCategoryList = productCategoryService.findAll(productCategory);
        return productCategoryList;
    }

    /**
     * 保存新增的数据
     * 
     * @param modelMap
     * @param productCategory
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("productCategory:productCategory:insert")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public String save(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            ProductCategory productCategory) throws Exception {
        if (!beanValidator(modelMap, productCategory)) {
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }

        // 查询相同父类下是否存在与当前名称重复的分类
        productCategory.setDelFlag("0");
        List<ProductCategory> productCategorys = productCategoryService.findList(productCategory);
        if (null != productCategorys && productCategorys.size() > 0) {
            modelMap.put("message", "分类名称已经存在");
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        if (StringUtils.isEmpty(productCategory.getSeq()))// 设置默认排序号
            productCategory.setSeq("1");
        productCategoryService.save(productCategory);
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 保存修改的数据
     * 
     * @param modelMap
     * @param productCategory
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("productCategory:productCategory:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public String update(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            ProductCategory productCategory) throws Exception {
        if (!beanValidator(modelMap, productCategory)) {
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        // 查询库中对象 判断当前需要修改的对象是否被删除
        ProductCategory pc = productCategoryService.findOne(productCategory.getId());
        if(null == pc || "1".equals(pc.getDelFlag())){
            modelMap.put("message", "对象已经被删除");
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        // 查询相同父类下是否存在与当前名称重复的分类
        ProductCategory queryProductCategory = new ProductCategory();
        queryProductCategory.setDelFlag("0");
        queryProductCategory.setParentId(pc.getParentId());
        queryProductCategory.setCategoryName(productCategory.getCategoryName());
        List<ProductCategory> productCategorys = productCategoryService.findList(queryProductCategory);
        if (null != productCategorys && productCategorys.size() > 0) {
            modelMap.put("message", "分类名称已经存在");
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
            return null;
        }
        
        productCategoryService.update(productCategory);
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 删除数据库
     * 
     * @param modelMap
     * @param productCategoryId
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("productCategory:productCategory:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public String delete(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap, String id)
            throws Exception {
        List<String> listId = Arrays.asList(id.split(","));
        productCategoryService.delete(listId);
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 假删除
     * 
     * @param modelMap
     * @param productCategory
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("productCategory:productCategory:delete")
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @ResponseBody
    public String remove(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            ProductCategory productCategory) throws Exception {
        productCategoryService.remove(productCategory);
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }

    /**
     * 导出Excel数据
     * 
     * @param modelMap
     * @param productCategory
     * @return
     * @throws Exception
     */
    // @RequiresPermissions("productCategory:productCategory:export")
    @RequestMapping(value = "/export")
    public String export(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
            ProductCategory productCategory) throws Exception {
        String fileName = DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
        productCategory.setDelFlag("0");
        List<ProductCategory> productCategoryList = productCategoryService.findAll(productCategory);
        new ExportExcel(null, ProductCategory.class).setDataList(productCategoryList).write(response, fileName).dispose();
        return null;
    }

    /**
     * 添加商品分类
     * 
     * @param request
     * @return
     * @throws Exception
     */
    // 请求数据格式{"categoryJson":{"parentId":"44b74eb39f634c4baff753ba353fb9b0","categoryName":"钢材","level":"1","seq":"1"}}
    @RequestMapping(value = "/addProdCategory", method = RequestMethod.POST)
    @ResponseBody
    public Result addProdCategory(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String json = request.getParameter("categoryJson");

        if (json != null && !json.equals("")) {
            ProductCategory productCategory = new Gson().fromJson(json, ProductCategory.class);
            if (null != productCategory) {
                productCategoryService.save(productCategory);
                return Result.success(null, "添加成功!");
            } else {
                return Result.failure("添加失败");
            }
        }
        return null;
    }

    /**
     * 刪除商品分類
     * 
     * @param session
     * @param request
     * @param categoryId
     *            商品分類id
     * @return
     */
    // 请求数据格式 {"id":"0"}
    @RequestMapping(value = "/deleteProdCategory", method = RequestMethod.POST)
    @ResponseBody
    public Result deleteProdCategory(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");

        // String id = (String) JSONPath.read(json, "$.id");
        if (id != null && !id.equals("")) {
            productCategoryService.delete(Arrays.asList(id.split(",")));
            return Result.success(null, "删除成功!");
        } else {
            return Result.failure("删除失败");
        }
    }

    /**
     * 修改商品种类
     * 
     * @param request
     * @param data
     *            商品种类后数据
     * @return
     */
    // 请求数据格式{"categoryJson":{"id":"44b74eb39f634c4baff753ba353fb9b0","parentId":"0","categoryName":"钢材","level":"1","seq":"1"}}
    @RequestMapping(value = "/updateProdCategory", method = RequestMethod.POST)
    @ResponseBody
    public Result updateProdCategory(HttpServletRequest request, HttpServletResponse response) {
        String json = request.getParameter("categoryJson");

        if (json != null && !json.equals("")) {
            String id = (String) JSONPath.read(json, "$.id");
            ProductCategory prodCategory = productCategoryService.findOne(id);
            prodCategory.setDelFlag("0");
            prodCategory.setCategoryName((String) JSONPath.read(json, "$.categoryName"));
            prodCategory.setLevel((String) JSONPath.read(json, "$.level"));
            prodCategory.setSeq((String) JSONPath.read(json, "$.seq"));
            productCategoryService.update(prodCategory);
            return Result.success(null, "修改成功");
        } else {
            return Result.failure("修改失败");
        }
    }

    /**
     * 查询所有商品分类
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/findAllProdCategory", method = RequestMethod.POST)
    @ResponseBody
    public Result findAllProdCategory(HttpServletRequest request, HttpServletResponse response, ProductCategory pCategory) {
    	pCategory.setDelFlag("0");
        List<ProductCategory> categorys = productCategoryService.findAll(pCategory);
        if (categorys != null && categorys.size() > 0) {
            return Result.success(categorys, "查询成功");
        } else {
            return Result.failure("查詢失敗");

        }

    }
}
